package com.gd.deron.smartrobot.baobao.wifi;

import java.util.List;

import com.gd.deron.smartrobot.baobao.BaseActivity;
import com.gd.deron.smartrobot.baobao.R;
import com.gd.deron.smartrobot.baobao.app.MyApplication;
import com.gd.deron.smartrobot.baobao.utils.ChatMessageUtil;
import com.gd.deron.smartrobot.baobao.utils.WifiAdminUtils;
import com.gd.deron.smartrobot.baobao.utils.WifiConnectUtils;
import com.gd.deron.smartrobot.baobao.wifi.SocketClient.ClientMsgListener;
import com.gd.deron.smartrobot.baobao.wifi.SocketServer.ServerMsgListener;
import com.gd.deron.smartrobot.baobao.wifi.WifiHotManager.OpretionsType;
import com.gd.deron.smartrobot.baobao.wifi.WifiHotManager.WifiBroadCastOperations;
import com.google.gson.Gson;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


public class WifiApAdminActivity extends BaseActivity implements WifiBroadCastOperations {

	private static String TAG = "WifiApAdminActivity";

	private Button wifiHotBtn;

	private Button chatBtn;

	private Button scanHotsBtn;

	private TextView statu;

	private WifiHotManager wifiHotM;

	private List<ScanResult> wifiList;

	private SocketClient client;

	private SocketServer server;

	private ListView listView;

	private WifiHotAdapter adapter;

	private boolean connected;

	private String mSSID;

	private Handler serverHandler;

	private Handler clientHandler;
	private boolean isContectWifi = false;
	private WifiAdminUtils mWifiAdmin;
	private String wifiName;
	private String wifiPas;
	private Gson gson;
	private View textEntryView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i(TAG, "into onCreate()");
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.actiivty_wifihotlist);

		initClientHandler();
		initServerHandler();
		
		mWifiAdmin = new WifiAdminUtils(WifiApAdminActivity.this);
		wifiHotM = WifiHotManager.getInstance(WifiApAdminActivity.this, WifiApAdminActivity.this);
		gson = new Gson();
		// 聊天室
		chatBtn = (Button) findViewById(R.id.chatHom);
		chatBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isContectWifi) {
					//saveData();
					//ChatMessageUtil.sendChatMsg(structChatMessage("Deroni+-developer", "deron123"));
				} else {
					Toast.makeText(WifiApAdminActivity.this, "wifi未连接", 0).show();
				}

			}
		});

		// 热点创建
		wifiHotBtn = (Button) findViewById(R.id.createHot);
		wifiHotBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				wifiHotM.startAWifiHot("deoron_baobao");
				initServer();
			}
		});

		// 热点扫描
		scanHotsBtn = (Button) findViewById(R.id.scanHots);
		scanHotsBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				wifiHotM.scanWifiHot();
			}
		});

		// 热点列表
		listView = (ListView) findViewById(R.id.listHots);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				ScanResult result = wifiList.get(position);
				mSSID = result.SSID;
				if(!isContectWifi){
					statu.setText("连接中...");
					Log.i(TAG, "into  onItemClick() SSID= " + result.SSID);
					wifiHotM.registerWifiConnectBroadCast();
					Log.i(TAG, "out  onItemClick() SSID= " + result.SSID);
					connectWifi(result, Global.PASSWORD);
				}else{
					showInputNameAndPas(result);
				}
				
			}
		});
		statu = (TextView) findViewById(R.id.hotTitleName);
		Log.i(TAG, "out onCreate()");
	}

	protected void showInputNameAndPas(final ScanResult result) {
		LayoutInflater factory = LayoutInflater.from(WifiApAdminActivity.this);
        textEntryView = factory.inflate(R.layout.wifiname_pas_dialog, null);
         AlertDialog dlg = new AlertDialog.Builder(WifiApAdminActivity.this)
         .setTitle("请输入密码！")
         .setView(textEntryView)
         .setPositiveButton("马上连接", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) {
               //TextView username = (TextView) textEntryView.findViewById(R.id.username_tv);
               EditText password = (EditText) textEntryView.findViewById(R.id.password_edit);
              // username.setText(mSSID);
               Log.e(TAG, "开始连接"+result.SSID);
               String inputPwd = password.getText().toString();
               //String inputUsername= username.getText().toString();
               if(!TextUtils.isEmpty(inputPwd)&&inputPwd!=""){
            	   wifiHotM.registerWifiConnectBroadCast();
    			   Log.i(TAG, "开始连接"+result.SSID);
    			   if (isContectWifi) {
   					saveData();
   					Toast.makeText(WifiApAdminActivity.this, "正在连接"+result.SSID, 0).show();
   					ChatMessageUtil.sendChatMsg(structChatMessage(result.SSID, inputPwd));
	   				} else {
	   					Toast.makeText(WifiApAdminActivity.this, "wifi未连接", 0).show();
	   				} 
    			   dialog.dismiss();
               }else{
            	   Toast.makeText(WifiApAdminActivity.this,"请输入密码！" , 0).show();
               }
             }
         })
         .setNegativeButton("取消", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int whichButton) {
                
             }
         })
         .create();
         dlg.show();
     }

	private String structChatMessage(String name, String pas) {

		ChatMessage msg = new ChatMessage();
		msg.setWifiName(name);
		msg.setWifiPassword(pas);

		return gson.toJson(msg);

	}

	private void connectWifi(ScanResult scanResult, String pas) {
		String desc = "";
		String descOri = scanResult.capabilities;
		if (descOri.toUpperCase().contains("WPA-PSK")) {
			desc = "WPA";
		}
		if (descOri.toUpperCase().contains("WPA2-PSK")) {
			desc = "WPA2";
		}
		if (descOri.toUpperCase().contains("WPA-PSK") && descOri.toUpperCase().contains("WPA2-PSK")) {
			desc = "WPA/WPA2";
		}

		if (desc.equals("")) {
			isConnectSelf(scanResult);
			return;
		}
		isConnect(scanResult, pas);
	}

	/**
	 * 有密码验证连接
	 * 
	 * @param scanResult
	 */
	private void isConnect(ScanResult scanResult, String pas) {
		if (mWifiAdmin.isConnect(scanResult)) {
			Toast.makeText(WifiApAdminActivity.this, "已連接", 0).show();
			statu.setText("已連接");
		} else {
			WifiConnectUtils.WifiCipherType type = null;
			if (scanResult.capabilities.toUpperCase().contains("WPA")) {
				type = WifiConnectUtils.WifiCipherType.WIFICIPHER_WPA;
			} else if (scanResult.capabilities.toUpperCase().contains("WEP")) {
				type = WifiConnectUtils.WifiCipherType.WIFICIPHER_WEP;
			} else {
				type = WifiConnectUtils.WifiCipherType.WIFICIPHER_NOPASS;
			}

			boolean isConnect = mWifiAdmin.connect(scanResult.SSID, pas, type);
		}
	}

	/**
	 * 无密码直连
	 * 
	 * @param scanResult
	 */
	private void isConnectSelf(ScanResult scanResult) {
		if (mWifiAdmin.isConnect(scanResult)) {
			// 已连接，显示连接状态对话框
			Toast.makeText(WifiApAdminActivity.this, "已連接", 0).show();
			statu.setText("已連接");
		} else {
			boolean iswifi = mWifiAdmin.connectSpecificAP(scanResult);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (iswifi) {
				Toast.makeText(WifiApAdminActivity.this, "连接成功>>>！", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(WifiApAdminActivity.this, "连接失败>>>！", Toast.LENGTH_SHORT).show();
			}
		}
	}

	private String intToIp(int i) {
		return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + ((i >> 24) & 0xFF);
	}


	@Override
	protected void onStart() {
		super.onStart();
	}




	// 扫描热点广播初始化
	@Override
	protected void onResume() {

		// wifiHotM.scanWifiHot();
		super.onResume();
	}

	// 监听返回键，退出程序
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Log.i(TAG, "into onBackPressed()");
			wifiHotM.unRegisterWifiScanBroadCast();
			wifiHotM.unRegisterWifiStateBroadCast();
			wifiHotM.disableWifiHot();
			this.finish();
			Log.i(TAG, "out onBackPressed()");
			return true;
		}
		return true;
	}

	@Override
	protected void onDestroy() {
		Log.i(TAG, "into onDestroy() ");
		if (adapter != null) {
			adapter.clearData();
			adapter = null;
		}
		if (server != null) {
			server.clearServer();
			server.stopListner();
			server = null;
			wifiHotM.disableWifiHot();

		}
		if (client != null) {
			client.clearClient();
			client.stopAcceptMessage();
			client = null;
			wifiHotM.deleteMoreCon(mSSID);
		}
		super.onDestroy();
	}

	// wifi 热点扫描回调
	@Override
	public void disPlayWifiScanResult(List<ScanResult> wifiList) {
		
		Log.i(TAG, "into 扫描结果回调函数");
		this.wifiList = wifiList;
		wifiHotM.unRegisterWifiScanBroadCast();
		refreshWifiList(wifiList);
		Log.i(TAG, "out 热点扫描结果 ： = " + wifiList);
		if (wifiList != null && wifiList.size() > 0) {
			for (ScanResult wifi : wifiList) {
				if (wifi.SSID.equals(wifiName)) {
					Toast.makeText(WifiApAdminActivity.this, "正在连接" + wifiName, 0).show();
					connectWifi(wifi, wifiPas);
				}
			}
		}

	}

	// wifi 连接回调
	@Override
	public boolean disPlayWifiConResult(boolean result, WifiInfo wifiInfo) {

		Log.i(TAG, "into 热点连接回调函数");
		wifiHotM.setConnectStatu(false);
		wifiHotM.unRegisterWifiStateBroadCast();
		wifiHotM.unRegisterWifiConnectBroadCast();
		initClient();
		Log.i(TAG, "out 热点链接回调函数");
		return false;
	}

	// wifi 热点连接、扫描在Wifi关闭的情况下，回调
	@Override
	public void operationByType(OpretionsType type, String SSID) {
		Log.i(TAG, "into operationByType！type = " + type);
		if (type == OpretionsType.CONNECT) {
			wifiHotM.connectToHotpot(SSID, wifiList, Global.PASSWORD);
		} else if (type == OpretionsType.SCAN) {
			wifiHotM.scanWifiHot();
		}
		Log.i(TAG, "out operationByType！");

	}

	// server 初始化
	private void initServer() {
		server = SocketServer.newInstance(12345, new ServerMsgListener() {
			Message msg = null;

			@Override
			public void handlerHotMsg(String hotMsg) {
				connected = true;
				Log.i(TAG, "server 初始化成功！");
				msg = clientHandler.obtainMessage();
				msg.obj = hotMsg;
				msg.what = 1;
				serverHandler.sendMessage(msg);
			}

			@Override
			public void handlerErorMsg(String errorMsg) {
				connected = false;
				Log.d(TAG, "server 初始化失败！");
				msg = clientHandler.obtainMessage();
				msg.obj = errorMsg;
				msg.what = 0;
				serverHandler.sendMessage(msg);
			}
		});
		server.beginListen();
	}

	// client 初始化
	private void initClient() {
		client = SocketClient.newInstance("192.168.43.1", 12345, new ClientMsgListener() {

			Message msg = null;

			@Override
			public void handlerErorMsg(String errorMsg) {
				connected = false;
				Log.d(TAG, "client 初始化失败！");
				msg = clientHandler.obtainMessage();
				msg.obj = errorMsg;
				msg.what = 0;
				clientHandler.sendMessage(msg);

			}

			@Override
			public void handlerHotMsg(String hotMsg) {
				connected = true;
				Log.i(TAG, "client 初始化成功！");
				msg = clientHandler.obtainMessage();
				msg.obj = hotMsg;
				msg.what = 1;
				clientHandler.sendMessage(msg);

			}
		});
		client.connectServer();
	}

	private void refreshWifiList(List<ScanResult> results) {
		Log.i(TAG, "into 刷新wifi热点列表");
		if (null == adapter) {
			Log.i(TAG, "into 刷新wifi热点列表 adapter is null！");
			adapter = new WifiHotAdapter(results, this);
			listView.setAdapter(adapter);
		} else {
			Log.i(TAG, "into 刷新wifi热点列表 adapter is not null！");
			adapter.refreshData(results);
		}
		Log.i(TAG, "out 刷新wifi热点列表");
	}

	private void saveData() {
		Log.i(TAG, "into saveData()");
		MyApplication.mAPP.client = this.client;
		MyApplication.mAPP.server = this.server;
		MyApplication.mAPP.wifiHotM = this.wifiHotM;
		Log.i(TAG, "out saveData() app client =" + MyApplication.mAPP.client);
	}

	private void initServerHandler() {
		serverHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if (msg.what == 0) {
					statu.setText("请创建热点");
				} else {
					statu.setText("请选择热点deron_baobao");
					String text = (String) msg.obj;
					try {
						ChatMessage chatMsg = gson.fromJson(text, ChatMessage.class);
						wifiName = chatMsg.getWifiName();
						wifiPas = chatMsg.getWifiPassword();
						Log.i(TAG, "into initServerHandler() handleMessage(Message msg) text = " + text);
						
						wifiHotM.closeAWifiHot();//先关闭热点再根据账号密码连接wifi
						//wifiHotM.registerWifiConnectBroadCast();
						boolean bool = mWifiAdmin.openWifi();
						new Handler().postDelayed(new Runnable() {
							
							@Override
							public void run() {
								Toast.makeText(WifiApAdminActivity.this, "开始搜索网络", 0).show();
								wifiHotM.scanWifiHot();
							}
						}, 3000);
						

					} catch (Exception e) {
						// TODO: handle exception
					}

				}
			}
		};
	}

	private void initClientHandler() {
		clientHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				Log.i(TAG, "into initClientHandler() handleMessage(Message msg)");
				if (msg.what == 0) {
					statu.setText("连接失败！");
					isContectWifi = false;
				} else {
					statu.setText("请连接热点deron_baobao!");
					Toast.makeText(WifiApAdminActivity.this, "请连接热点deron_baobao", 1).show();
					isContectWifi = true;
					String text = (String) msg.obj;
					Toast.makeText(WifiApAdminActivity.this, text, 0).show();
					Log.i(TAG, "into initClientHandler() handleMessage(Message msg) text =" + text);
				}
			}
		};
	}
	
	@Override
	public void wifiConnectSUccessfull() {
		super.wifiConnectSUccessfull();
		Toast.makeText(WifiApAdminActivity.this, "wifi连接成功", 0).show();
	}
	@Override
	public void wifiConnectFailed() {
		super.wifiConnectFailed();
		Toast.makeText(WifiApAdminActivity.this, "wifi连接失败", 0).show();
	}
}
